#!/usr/bin/env jruby

$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + '/../lib'))

require 'rubygems'
gem 'spotify-api'

require 'clients/lastfm'
require 'clients/spotify'

# a demo app which grabs tracks from last.fm and creates a spotify 
# playlist based on tracks popular in a city

# to batch create playlists, use lastfm_metro_playlists.rb
if __FILE__ == $0
  city = ARGV.shift or raise "#{$0} <city,country>"

  metro,country = *city.split(',')
  
  puts "fetching last.fm tracks for #{metro}, #{country}"
  unique = true
  tracks = LastFM.metro_track_chart(metro,country, unique)
  
  puts "resolving spotify ids"
  spotify_tracks = begin 
    Spotify.resolve(tracks.map { |t| [t["name"], t["artist"]["name"]] })
  rescue Errno::ECONNREFUSED 
    fail "Could not connect to spotify-api server. Make sure it it running."
  end
  
  if spotify_tracks.size > 0
    puts "creating playlist with #{spotify_tracks.size} tracks"
    puts Spotify.create_playlist("chart for #{metro}, #{country}", spotify_tracks.map { |t| t['id'] })  
  end
end
